import 'dart:io';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import '../index.dart';

/// 苹果登录服务
class AppleSignInService {
  /// 检查是否支持苹果登录
  static Future<bool> isAvailable() async {
    // 只有iOS 13.0+和macOS 10.15+支持苹果登录
    if (Platform.isIOS) {
      return await SignInWithApple.isAvailable();
    }
    return false;
  }

  /// 执行苹果登录
  static Future<AppleSignInResult?> signIn() async {
    try {
      // 检查是否支持苹果登录
      if (!await isAvailable()) {
        return AppleSignInResult(
          success: false,
          error: 'Apple Sign In is not available on this device',
        );
      }

      // 请求苹果登录
      final credential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );

      // 处理登录结果
      if (credential.userIdentifier != null) {
        // 构建用户信息
        String displayName = '';
        if (credential.givenName != null || credential.familyName != null) {
          displayName =
              '${credential.givenName ?? ''} ${credential.familyName ?? ''}'
                  .trim();
        }

        // 如果没有显示名称，使用默认名称
        if (displayName.isEmpty) {
          displayName = 'Apple User';
        }

        return AppleSignInResult(
          success: true,
          userIdentifier: credential.userIdentifier!,
          email: credential.email,
          displayName: displayName,
          identityToken: credential.identityToken,
          authorizationCode: credential.authorizationCode,
        );
      } else {
        return AppleSignInResult(
          success: false,
          error: 'Failed to get user identifier from Apple',
        );
      }
    } catch (e) {
      // 处理用户取消登录的情况
      if (e is SignInWithAppleAuthorizationException) {
        if (e.code == AuthorizationErrorCode.canceled) {
          return AppleSignInResult(
            success: false,
            error: 'User canceled Apple Sign In',
            isCanceled: true,
          );
        }
      }

      return AppleSignInResult(
        success: false,
        error: 'Apple Sign In failed: ${e.toString()}',
      );
    }
  }

  /// 创建或获取苹果登录用户
  static UserEntity createAppleUser({
    required String userIdentifier,
    String? email,
    String? displayName,
  }) {
    // 生成用户名（使用Apple ID的前6位或显示名称的前6位）
    String username = displayName ?? 'Apple';
    if (username.length > 6) {
      username = username.substring(0, 6);
    }

    // 确保用户名唯一
    username = _generateUniqueUsername(username);

    return UserEntity(
      id: 'apple_$userIdentifier',
      username: username,
      password: '', // 苹果登录不需要密码
      avatar: MyImages.mark, // 使用默认头像
      share: [],
      isVip: false,
      like: [],
      reportedPosts: [],
      reportedUsers: [],
      reportedChats: [],
    );
  }

  /// 生成唯一用户名
  static String _generateUniqueUsername(String baseName) {
    // 这里可以添加逻辑来确保用户名唯一
    // 暂时返回基础名称，实际使用时可能需要添加数字后缀
    return baseName;
  }
}

/// 苹果登录结果
class AppleSignInResult {
  final bool success;
  final String? userIdentifier;
  final String? email;
  final String? displayName;
  final String? identityToken;
  final String? authorizationCode;
  final String? error;
  final bool isCanceled;

  AppleSignInResult({
    required this.success,
    this.userIdentifier,
    this.email,
    this.displayName,
    this.identityToken,
    this.authorizationCode,
    this.error,
    this.isCanceled = false,
  });

  @override
  String toString() {
    return 'AppleSignInResult(success: $success, userIdentifier: $userIdentifier, email: $email, displayName: $displayName, error: $error)';
  }
}
